package com.tanhua.dubbo.api;

import cn.hutool.core.util.ObjectUtil;
import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/10/30
 */
@DubboService
public class FriendApiImpl implements FriendApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveContacts(Long userId, Long friendId) {
        //向friend表中添加数据(双向)
        save(userId, friendId);
        save(friendId, userId);
    }

    @Override
    public List<Friend> getContacts(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Long skip = Long.valueOf((page - 1) * pagesize);
        Query query = Query.query(criteria).skip(skip).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query, Friend.class);
    }

    @Override
    public void removeFriend(Long userId, Long friendId) {
        remove(userId, friendId);
        remove(friendId, userId);
    }

    /**
     * 从friend表中双向删除数据
     * @param userId
     * @param friendId
     */
    private void remove(Long userId, Long friendId) {
        Criteria criteria = Criteria.where("userId").is(userId).and("friendId").is(friendId);
        Friend friend = mongoTemplate.findOne(Query.query(criteria), Friend.class);
        if (ObjectUtil.isNotEmpty(friend)) {
            mongoTemplate.remove(friend);
        }
    }

    /**
     * 向friend表中双向添加数据
     * @param userId
     * @param friendId
     */
    private void save(Long userId, Long friendId) {
        Criteria criteria = Criteria.where("userId").is(userId).and("friendId").is(friendId);
        Boolean exists = mongoTemplate.exists(Query.query(criteria), Friend.class);
        if (!exists) {
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
    }
}
